package com.mikey.demo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author :Mikey
 * @description :
 * @create :2022-09-19 17:42:00
 */
public class SaleTicketDemo1 {
    public static void main(String[] args) {
        //并发，多个线程操作同一个资源类，把资源丢入线程
        Ticket1 ticket1 = new Ticket1();
        //@FunctionalInterface 函数式接口，jdk1.8 lamda表达式(参数)->{代码}
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket1.sale();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket1.sale();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket1.sale();
            }
        }, "C").start();
    }
}

//资源类，oop，解除耦合
class Ticket1 {
    //属性方法
    private int number = 50;

    Lock lock = new ReentrantLock();

    public void sale() {
        lock.lock();//加锁
        try {//业务代码
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了" + number-- + "票" + "剩余：" + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//解锁
        }
    }
}

